<template>
  <div class="table-page">
    <GiTable
      row-key="id"
      title="会议室管理"
      :data="dataList"
      :columns="columns"
      :loading="loading"
      :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
      :pagination="pagination"
      :disabled-tools="['size']"
      :disabled-column-keys="['name']"
      @refresh="tableSearch"
    >
      <template #custom-left>
        <a-input v-model="queryForm.name" placeholder="请输入会议室名称" allow-clear @input="tableSearch">
          <template #prefix><icon-search /></template>
        </a-input>
        <a-button @click="reset">
          <template #icon><icon-refresh /></template>
          <template #default>重置</template>
        </a-button>
      </template>
      <template #custom-right>
        <a-button v-permission="['system:meetRoom:add']" type="primary" @click="onAdd">
          <template #icon><icon-plus /></template>
          <template #default>新增</template>
        </a-button>
      </template>
      <template #imageUrl="{ record }">
        <a-image width="200px" height="100px" :src="record.imageUrl" :preview="true" />
      </template>
      <template #status="{ record }">
        <a-tag :color="record.status === 'enabled' || record.status === 1 ? 'green' : 'red'">
          {{ record.status === 'enabled' || record.status === 1 ? '开启' : '禁用' }}
        </a-tag>
      </template>
      <template #action="{ record }">
        <a-space v-if="has.hasPermOr(['system:meetRoom:updateMeetingRoom'])">
          <a-link v-permission="['system:meetRoom:updateMeetingRoom']" title="修改" @click="onUpdate(record)">修改</a-link>
        </a-space>
      </template>
    </GiTable>

    <MeetingRoomAddModal ref="MeetingRoomAddModalRef" @save-success="tableSearch" />

    <!-- 禁用会议室弹窗 -->
    <a-modal
      v-model:visible="forbidScreenModalVisible"
      title-align="start"
      title="会议室禁用"
      width="600px"
      :modal-style="{ maxHeight: '80vh' }"
      :body-style="{ padding: '16px', maxHeight: 'calc(80vh - 100px)', overflow: 'auto' }"
      @ok="handleForbidScreen"
      @cancel="cancelForbidScreen"
    >
      <div>
        <a-form :model="forbidScreenForm">
          <a-form-item label="会议室信息">
            <div v-if="currentMeetingRoom" style="padding: 12px; background-color: #f5f5f5; border-radius: 4px;">
              <p><strong>会议室名称：</strong>{{ currentMeetingRoom.meetingRoomName || currentMeetingRoom.name || '未知会议室' }}</p>
            </div>
          </a-form-item>

          <a-form-item label="门口屏操作">
            <a-radio-group v-model="forbidScreenForm.status" direction="vertical">
              <a-radio :value="0">自定义门口屏图片</a-radio>
              <a-radio :value="2">默认禁用门口屏图片</a-radio>
              <a-radio :value="1">恢复启用</a-radio>
</a-radio-group>
          </a-form-item>

          <a-form-item v-if="forbidScreenForm.status === 0" label="上传门口屏图片">
            <div>
              <input
                type="file"
                accept="image/*"
                @change="handleImageUpload"
              />
              <div style="margin-top: 5px; color: #666; font-size: 12px;">
                请上传小于2M，分辨率1280*800大小的图片，图片将显示在会议室门口屏上
              </div>
            </div>
          </a-form-item>

          <a-form-item v-if="uploadedImage && forbidScreenForm.status === 0" label="图片预览">
            <img :src="uploadedImage" style="max-width: 100%; max-height: 300px;" />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { debounce } from 'lodash-es'
import { Message } from '@arco-design/web-vue'
import MeetingRoomAddModal from './MeetingRoomAddModal.vue'
import { type MeetingRoomQuery, type MeetingRoomResp, exportMeetingRoom, forbidMeetingRoomScreen, listMeetingRoom } from '@/apis/meet'
import { uploadAvatarFile } from '@/apis/common/common'
import type { TableInstanceColumns } from '@/components/GiTable/type'
import { useDownload, useTable } from '@/hooks'
import { isMobile } from '@/utils'
import has from '@/utils/has'

defineOptions({ name: 'MeetingRoom' })

const queryForm = reactive<MeetingRoomQuery>({
  name: undefined,
  sort: ['roomSort,asc', 'createTime,desc']
})

const {
  tableData: dataList,
  loading,
  pagination,
  search
} = useTable((page) => listMeetingRoom({ ...queryForm, ...page }), { immediate: true })

const columns: TableInstanceColumns[] = [
  { title: '会议室名称', dataIndex: 'meetingRoomName', slotName: 'meetingRoomName' },
  { title: '所属办公楼', dataIndex: 'officeBuildingName', slotName: 'officeBuildingName' },
  { title: '所属厂区', dataIndex: 'factoryName', slotName: 'factoryName' },
  { title: '楼层', dataIndex: 'floor', slotName: 'floor' },
  { title: '会议室容量', dataIndex: 'roomCapacity', slotName: 'roomCapacity' },
  { title: '状态', dataIndex: 'status', slotName: 'status' },
  { title: '会议室图片', dataIndex: 'imageUrl', slotName: 'imageUrl' },
  {
    title: '操作',
    slotName: 'action',
    width: 180,
    align: 'center',
    fixed: !isMobile() ? 'right' : undefined
  }
]

const tableSearch = debounce(search, 500)

// 重置
const reset = () => {
  queryForm.name = undefined
  search()
}

// 导出
const _onExport = () => {
  useDownload(() => exportMeetingRoom(queryForm))
}

const MeetingRoomAddModalRef = ref<any>()
// 新增
const onAdd = () => {
  MeetingRoomAddModalRef.value?.onAdd()
}

// 修改
const onUpdate = (record: MeetingRoomResp) => {
  MeetingRoomAddModalRef.value?.onUpdate(record.id, record.factoryId)
}

// 禁用会议室相关状态
const forbidScreenModalVisible = ref(false)
const currentMeetingRoom = ref<MeetingRoomResp | null>(null) // 当前选中的会议室
const forbidScreenForm = reactive({
  status: 0 // 0自定义图片禁用   1恢复启用     2默认图片禁用
})
const uploadedImage = ref<string | null>(null) // 上传的图片
const imageFile = ref<File | null>(null) // 图片文件对象

// 重置禁用会议室表单
const resetForbidScreenForm = () => {
  currentMeetingRoom.value = null
  forbidScreenForm.status = 0
  uploadedImage.value = null
  imageFile.value = null
}

// 处理图片上传（参考门口屏功能）
const handleImageUpload = (event) => {
  const file = event.target.files?.[0]

  if (!file) {
    Message.error('请选择图片')
    return
  }

  // 检查文件大小（2MB限制）
  if (file.size > 2 * 1024 * 1024) {
    Message.error('图片大小不能超过2MB')
    return
  }

  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    Message.error('请选择图片文件')
    return
  }

  imageFile.value = file
  const reader = new FileReader()
  reader.onload = (e) => {
    if (e.target) {
      uploadedImage.value = e.target.result as string
    }
  }
  reader.readAsDataURL(file)
}

// 执行禁用会议室
const handleForbidScreen = async () => {
  if (!currentMeetingRoom.value) {
    Message.error('未选择会议室')
    return
  }

  try {
    let imageUrl = ''

    // 如果有上传图片，先上传图片获取URL
    if (imageFile.value) {
      const formData = new FormData()
      formData.append('file', imageFile.value)

      try {
        // 使用统一的图片上传API
        const uploadRes = await uploadAvatarFile(formData)

        // 兼容后端返回code为0、'0'、200、'200'都视为成功
        if (!uploadRes || !(String(uploadRes.code) === '200' || String(uploadRes.code) === '0')) {
          console.error('图片上传失败:', uploadRes)
          Message.error(uploadRes?.msg || '图片上传失败')
          return
        }

        imageUrl = uploadRes.data
      } catch (error) {
        console.error('图片上传错误:', error)
        Message.error('图片上传失败')
        return
      }
    }

    // 调用禁用接口
    const res = await forbidMeetingRoomScreen({
      id: Number(currentMeetingRoom.value.id),
      url: imageUrl,
      status: forbidScreenForm.status
    })

    if (res.success || String(res.code) === '0') {
      Message.success('会议室禁用设置成功')
      forbidScreenModalVisible.value = false
      resetForbidScreenForm()
      tableSearch() // 刷新表格
    } else {
      Message.error(res.msg || '操作失败')
    }
  } catch (error) {
    console.error('禁用会议室失败:', error)
    Message.error('操作失败')
  }
}

// 取消禁用会议室弹窗
const cancelForbidScreen = () => {
  forbidScreenModalVisible.value = false
  resetForbidScreenForm()
}
</script>

<style lang="scss" scoped>
.table-page {
  padding: 16px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);

  :deep(.arco-input-wrapper) {
    width: 240px;
    margin-right: 16px;
  }
}
</style>
